<template>
  <div>
    <el-collapse-transition>
      <div v-show="btnGroup.search" class="main-box search-box">
        <el-form
          class="troila-form"
          ref="searchInfo"
          :model="searchObj"
          :inline="true"
          label-width="100px"
        >
          <el-form-item
            label="登录名称"
            prop="loginName"
            class="troila-select-inline"
          >
            <el-input
              v-setwidth
              placeholder="请输入登录名称"
              v-model="searchObj.loginName"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="邮箱账号"
            prop="email"
            class="troila-select-inline"
          >
            <el-input
              v-setwidth
              placeholder="请输入邮箱账号"
              v-model="searchObj.email"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="手机号码"
            prop="phone"
            class="troila-select-inline"
          >
            <el-input
              v-setwidth
              placeholder="请输入手机号码"
              v-model="searchObj.phone"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item
            label="用户状态"
            prop="status"
            class="troila-select-inline"
          >
            <el-select
              v-setwidth
              placeholder="请选择用户状态"
              v-model="searchObj.status"
              clearable
              popper-class="troila-popper"
            >
              <el-option
                v-for="(item, index) in userList"
                :key="index"
                :label="item.dictName"
                :value="item.dictCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" class="troila-select-inline">
            <el-date-picker
              v-model="time"
              v-setwidth
              placeholder="请选择"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
              @change="changeDate"
              type="daterange"
              popper-class="troila-popper"
            ></el-date-picker>
          </el-form-item>
          <el-form-item class="searchBtn">
            <el-button class="cancelBtn" @click="resetForm">重置</el-button>
            <el-button type="primary" @click="submitSearch">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-collapse-transition>
    <div class="troila-group">
      <select-group
        v-model="btnGroup"
        :row="allTitle"
        :row-choose="chooseTitle"
        @rowChange="
          (arr) => {
            chooseTitle = arr
          }
        "
        @refresh="getList"
      />
    </div>
    <div class="main-box table-box">
      <div class="table-box-title ClearFloat">
        <i class="title-font">查询结果</i>
        <div class="troila-form">
          <el-button
            type="primary"
            v-limit="`system:userManage:add`"
            @click="btnClick('add')"
            >新增</el-button
          >
          <el-button
            type="primary"
            v-limit="`system:userManage:template`"
            @click="downloadExcel"
            >模板下载</el-button
          >
          <el-upload
            class="upload"
            action="1"
            :before-upload="beforeUploadFile"
            :http-request="uploadFile"
            :show-file-list="false"
          >
            <el-button type="primary" v-limit="`system:userManage:import`"
              >导入</el-button
            >
          </el-upload>

          <el-button
            type="primary"
            v-limit="`system:userManage:export`"
            @click="exportUser"
            >导出</el-button
          >
          <el-button
            type="primary"
            v-limit="`system:userManage:batchStart`"
            @click="btnClick('batchStart')"
            >批量启用</el-button
          >
          <el-button
            type="primary"
            v-limit="`system:userManage:batchStop`"
            @click="btnClick('batchStop')"
            >批量停用</el-button
          >
        </div>
      </div>
      <unit-table
        v-if="!btnGroup.card"
        selection
        index
        :loading="loading"
        :title="tableTitle"
        :data="tableData"
        :opera="4"
        :operation="tableOperation"
        :dictionary="dictionary"
        @return="tableReturn"
        :page="pager.page"
      />
      <unit-cards
        v-if="btnGroup.card"
        selection
        :loading="loading"
        :title="tableTitle"
        :data="tableData"
        :opera="4"
        :operation="tableOperation"
        :dictionary="dictionary"
        @return="tableReturn"
        :page="pager.page"
      />
      <pagination
        v-show="pager.total > pager.size"
        :pager="pager"
        @query="getList"
        ref="Pagerpagination"
      ></pagination>
    </div>
    <dialog-form v-model="showForm" @formConfirm="formConfirm" ref="userForm" />
    <dialog-role v-model="showRole" @roleConfirm="roleConfirm" ref="userRole" />
  </div>
</template>
<script>
import dialogForm from './dialog/userForm'
import dialogRole from './dialog/userRole'
import { downloadFile } from '@/assets/js/utils'
import { grobalbaseUrl } from '@/https/api/baseUrl'
export default {
  name: 'userManage',
  components: {
    dialogForm,
    dialogRole,
  },
  data() {
    return {
      searchObj: {
        loginName: '',
        email: '',
        phone: '',
        status: '',
        dateBegin: '',
        dateEnd: '',
      }, //搜索参数
      searchRes: {}, //搜索储存值
      loading: false,
      time: null, //时间组件值
      btnGroup: {
        //按钮组
        search: true,
        refresh: false,
        card: false,
      },
      pager: {
        // 页码
        total: 0,
        page: 1, //当前第几页
        size: 10, //每页显示的条数
      },
      dictionary: {
        // 字典信息
        // sex: [
        //   { dictName: '男', dictCode: '1' },
        //   { dictName: '女', dictCode: '0' },
        // ],
        // status: [
        // { dictName: '启用', dictCode: '1' },
        // { dictName: '停用', dictCode: '0' },
        // ],
        /*  roleList: [
                    { dictName: '角色1', dictCode: '1' },
                    { dictName: '角色2', dictCode: '2' },
                    { dictName: '角色3', dictCode: '3' },
                    { dictName: '角色4', dictCode: '4' },
                    { dictName: '角色5', dictCode: '5' },
                ], */
      },
      allTitle: [
        // 全部可显示表头
        {
          label: '登录名称', //*表头名称
          code: 'loginName', //*对应数据项
          tooltip: true, //超出显示浮层
          sort: true, //是否显示排序
          width: 110, //最小宽
        },
        {
          label: '用户名称',
          code: 'userName',
          tooltip: true,
          width: 110,
        },
        {
          label: '性别',
          code: 'sex',
          dict: 'sex', //需要查询字典对应的key
          width: 60,
        },
        {
          label: '邮箱账号',
          code: 'email',
          tooltip: true,
          width: 110,
        },
        {
          label: '手机号码',
          code: 'phone',
          tooltip: true,
        },
        {
          label: '用户状态',
          code: 'status',
          dict: 'status',
          style: {
            //该项style
            color: { value: '#FF4A4A', result: 0 },
          },
        },
        /*   {
                    label: '角色',
                    code: 'roleId',
                    dict: 'roleList',
                    tooltip: true,
                    sort: true,
                    width: 110,
                }, */
        {
          label: '创建时间',
          code: 'createTime',
          tooltip: true,
          sort: true,
          width: 110,
          format: (item, key) => {
            return this.toTime(item[key])
          },
        },
        {
          label: '创建人',
          code: 'createBy',
          tooltip: true,
          sort: true,
          width: 110,
        },
        {
          label: '修改时间',
          code: 'updateTime',
          tooltip: true,
          sort: true,
          width: 110,
          format: (item, key) => {
            return this.toTime(item[key])
          },
        },
        {
          label: '修改人',
          code: 'updateBy',
          tooltip: true,
          sort: true,
          width: 110,
        },
      ],
      chooseTitle: [
        //被选中显示表头
        'loginName',
        'userName',
        'sex',
        'email',
        'phone',
        'status',
        'createTime',
      ],
      tableData: [
        //表格数据
        /*  {
            id: '1',
            loginName: 'zhouyu',
            userName: '周瑜',
            sex: '1',
            email: 'zhouyu@sanguo.com',
            phone: '13012345678',
            status: '2',
            roleId: ['1', '3'],
            createTime: '2020-07-15 10:28'
        },
        {
            id: 2,
            loginName: 'zhugeliang',
            userName: '诸葛亮',
            sex: '1',
            email: 'zhugeliang@sanguo.com',
            phone: '13012345678',
            status: '1',
            roleId: ['2', '3'],
            createTime: '2020-07-15 10:28'
        } */
      ],
      tableOperation: [
        //表格操作
        // *code 对应图标, label 对应浮层显示文字, show 判断是否显示, color 图标颜色
        { code: 'edit', limit: 'system:userManage:edit' },
        {
          code: 'refresh',
          label: '重置密码',
          limit: 'system:userManage:resize',
        },
        {
          code: 'user',
          label: '分配角色',
          limit: 'system:userManage:user',
        },
        {
          code: 'start',
          label: '启用',
          limit: 'system:userManage:start',
          show: (row) => {
            return row.status == 0
          },
        },
        {
          code: 'stop',
          label: '停用',
          limit: 'system:userManage:stop',
          color: '#D13633',
          show: (row) => {
            return row.status == 1
          },
        },
      ],
      selection: [], //表格选中行
      showForm: false, //弹窗显示-新建修改
      showRole: false, //弹窗显示-分配角色
      editId: '',
      userId: '',
    }
  },
  computed: {
    tableTitle() {
      //表格表头
      return this.allTitle.filter(
        (item) => this.chooseTitle.indexOf(item.code) > -1
      )
    },
    userList() {
      let list = this.$store.state.dictionary.user_status
      if (!list) {
        this.$store.dispatch('dictionary/getDict', 'user_status')
      }
      this.dictionary.status = list
      let list1 = this.$store.state.dictionary.user_sex
      if (!list1) {
        this.$store.dispatch('dictionary/getDict', 'user_sex')
      }
      this.dictionary.sex = list1
      return list ? list : []
    },
  },
  methods: {
    // 获取列表
    getList() {
      let param = {
        pageNum: this.pager.page, //当前页
        pageSize: this.pager.size, //每页多少条
        ...this.searchRes,
      }
      this.loading = true
      setTimeout(() => {
        this.loading = false
        this.pager.total = 4
        this.tableData = [{}, {}, {}, {}]
      }, 100)
      return
      this.API.userManage
        .pageList(param)
        .then((res) => {
          // console.log(res)
          if (res.code === 1) {
            this.loading = false
            this.pager.total = res.data.total ? res.data.total : 0
            this.tableData = res.data.records
          } else {
            this.loading = false
          }
        })
        .catch((e) => {
          // console.log(e)
          this.loading = false
        })
    },
    // 日期控件操作
    changeDate() {
      // console.log(this.time)
    },
    // 重置
    resetForm() {
      // this.searchObj = {}
      this.$refs.searchInfo.resetFields()
      this.searchObj.dateBegin = ''
      this.searchObj.dateEnd = ''
      this.time = []
      this.searchRes = {}
      this.pager.page = 1
      this.getList()
    },
    // 搜索
    submitSearch() {
      this.searchRes = {
        ...this.searchObj,
        dateBegin: this.time && this.time.length > 0 ? this.time[0] : '',
        dateEnd: this.time && this.time.length > 0 ? this.time[1] : '',
      }
      this.pager.page = 1
      this.getList()
    },
    // 按钮操作
    btnClick(method) {
      // console.log(method)
      let text = ''
      switch (method) {
        case 'add':
          this.showForm = true
          this.editId = ''
          return
        case 'batchStart':
          text = '启用'
          break
        case 'batchStop':
          text = '停用'
          break
        default:
          return
      }
      let name = this.selection.map((v) => `${v.userName}(${v.loginName})`)
      this.selection.length > 0
        ? this.$confirmFn(
            `您确定${text}以下用户吗？<div>${name.join('、')}</div>`,
            '提示',
            {
              callback: (action, instance) => {
                // console.log(action, instance)
                if (action == 'cancel ') {
                  return
                } else if (action == 'confirm') {
                  // console.log(this.selection)
                  let idList = this.selection.map((v) => v.id).join(',')
                  // console.log(idList, this.selection)
                  this.updateStatus({
                    ids: idList,
                    status: text === '启用' ? '1' : '0',
                  })
                }
              },
            }
          )
        : this.$alertFn.error(`请选择需要${text}的数据 ！`)
    },
    // 表格操作
    tableReturn(method, { row, prop, order, selection }) {
      // console.log(method, row, prop, order, selection)
      let text = '',
        text_ = ''
      switch (method) {
        case 'edit':
          this.showForm = row
          this.editId = row.id
          return
        case 'user':
          this.showRole = row
          this.userId = row.id
          return
        case 'refresh':
          this.$confirmFn(
            `您确定为<span class='light'>${row.userName}(${row.loginName})</span>重置密码吗？`,
            '提示',
            {
              callback: (action, instance) => {
                // console.log(method, row)
                if (action == 'cancel ') {
                  return
                } else if (action == 'confirm') {
                  this.API.userManage
                    .resetPassword({ id: row.id })
                    .then((res) => {
                      // console.log(res)
                      if (res.code === 1) {
                        this.getList()
                        this.$alertFn.success(`密码重置成功 ！`)
                      } else {
                        this.$alertFn.error(`密码重置失败，请稍后再试 ！`)
                      }
                    })
                    .catch((e) => {
                      // console.log(e)
                      // this.$alertFn.error(`密码重置失败，请稍后再试 ！`)
                    })
                }
              },
            }
          )
          return
        case 'selection':
          this.selection = [...selection]
          return
        case 'start':
          text = '启用'
          break
        case 'stop':
          text = '停用'
          break

        default:
          return
      }
      this.$confirmFn(
        `您确定要${text}用户<span class='light'>${row.userName}(${row.loginName})</span>吗？`,
        '提示',
        {
          callback: (action, instance) => {
            // console.log(method, row)
            if (action == 'cancel ') {
              return
            } else if (action == 'confirm') {
              // console.log(row.id)
              this.updateStatus({
                ids: row.id.toString(),
                status: text === '启用' ? '1' : '0',
              })
            }
          },
        }
      )
    },
    formConfirm(data) {
      // console.log(data)
      if (this.editId) {
        this.editFormConfirm(data)
      } else {
        this.addFormConfirm(data)
      }
    },
    addFormConfirm(data) {
      //新增
      // console.log(data)
      this.API.userManage
        .addUser(data)
        .then((res) => {
          // console.log(res)
          if (res.code == '1') {
            this.showForm = false
            this.$refs.userForm.ajaxIng = false
            this.$alertFn.success('添加用户成功')
            this.resetForm()
          } else {
            this.$refs.userForm.ajaxIng = false
          }
        })
        .catch((error) => {
          // console.log(error)
          this.$refs.userForm.ajaxIng = false
        })
    },
    editFormConfirm(data) {
      //修改
      // console.log(data)
      let params = {
        ...data,
        id: this.editId,
      }
      this.API.userManage
        .updateUser(params)
        .then((res) => {
          if (res.code == '1') {
            this.showForm = false
            this.$refs.userForm.ajaxIng = false
            this.$alertFn.success('修改用户成功')
            this.resetForm()
          } else {
            this.$refs.userForm.ajaxIng = false
          }
        })
        .catch((error) => {
          this.$refs.userForm.ajaxIng = false
        })
    },
    roleConfirm(data) {
      // console.log(data)
      let param = {
        rodeId: data.roleId,
        userId: this.userId,
      }
      this.API.userManage
        .dispatchRole(param)
        .then((res) => {
          // console.log(res)
          if (res.code === 1) {
            this.showRole = false
            this.$refs.userRole.ajaxIng = false
            this.getList()
            this.$alertFn.success(`分配角色成功 ！`)
          } else {
            this.$refs.userRole.ajaxIng = false
          }
        })
        .catch((e) => {
          this.$refs.userRole.ajaxIng = false
        })
    },
    updateStatus(param) {
      this.API.userManage
        .updateStatus(param)
        .then((res) => {
          // console.log(res)
          if (res.code === 1) {
            this.getList()
            this.$alertFn.success(`切换用户状态成功 ！`)
          } else {
            this.$alertFn.error(`切换用户状态失败，请稍后再试 ！`)
          }
        })
        .catch((e) => {
          // this.$alertFn.error(`切换用户状态失败，请稍后再试 ！`)
        })
    },
    exportUser() {
      //导出
      let params = {
        ...this.searchObj,
        dateBegin: this.time && this.time.length > 0 ? this.time[0] : '',
        dateEnd: this.time && this.time.length > 0 ? this.time[1] : '',
      }
      this.API.userManage
        .exportUser(params)
        .then((res) => {
          // console.log(res)
          if (res.data) {
            // window.location.href=`${grobalbaseUrl.baseUrl}/download/${res.data}/操作日志`;
            downloadFile(
              `${grobalbaseUrl.baseUrl}/download/${res.data}/导出用户`,
              null,
              'url'
            )
          } else {
            this.$alertFn.error('导出失败')
          }
        })
        .catch((e) => {
          // this.$alertFn.error('导出失败')
        })
    },
    downloadExcel() {
      //模板下载
      // downloadFile(
      //   `${grobalbaseUrl.baseUrl}/TSysUser/downloadExcel`,
      //   null,
      //   'url'
      // )
      this.API.userManage.template().then((res) => {
        downloadFile(res.data, '用户导入模板.xlsx', 'excel')
      })

      // this.API.logManage
      //   .exportOperation({})
      //   .then((res) => {
      //     console.log(res.data)
      //     if (res.data) {
      //       console.log(res.data)
      //       downloadFile(
      //         `${grobalbaseUrl.baseUrl}/download/用户导入模板`,
      //         null,
      //         'url'
      //       )
      //     } else {
      //       this.$alertFn.error('导出失败')
      //     }
      //   })
      //   .catch((e) => {
      //     // this.$alertFn.error('导出失败')
      //   })
    },
    beforeUploadFile(file) {
      // console.log(file)
      const isEXCEL =
        file.type ===
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isEXCEL) {
        this.$alertFn.error('只能导入 excel文件!')
      }
      return isEXCEL
    },
    uploadFile(data) {
      // console.log(data)
      // let vueObj = this;
      let file = data.file
      // console.log(file)
      // const formData = new FormData()
      // formData.append('file', file)
      // console.log(formData)
      this.API.userManage.importExcel({ uploadFile: file }).then((res) => {
        if (res.code == '1') {
          this.$message.success('上传成功')
          this.resetForm()
        }
      })
    },
  },
  created() {
    this.submitSearch()
  },
  mounted() {},
  destroyed() {},
}
</script>
<style scoped>
.upload {
  display: inline-block;
}
</style>
